<script lang="ts" setup>
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput, FormInstance, FormRules } from 'element-plus'
import { computed, reactive, ref } from 'vue'
import { useDictStore } from '../store'
import { Dict } from '../data'

const dict = useDictStore()

const title = computed(() => (dict.form.id ? '新增字典' : '更新字典'))

const rules = reactive<FormRules<Pick<Dict, 'dictName' | 'dictType' | 'description'>>>({
  dictName: [
    {
      required: true,
      trigger: 'blur',
      message: '字典名称不能为空',
      whitespace: false,
    },
  ],
  dictType: [
    {
      required: true,
      trigger: 'blur',
      message: '字典类型不能为空',
      whitespace: false,
    },
  ],
  description: [
    {
      required: false,
      whitespace: false,
    },
  ],
})

const formRef = ref<FormInstance>()

const onClickSubmitForm = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) dict.onSubmitUpdate()
  })
}

const onResetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  dict.onResetForm()
}
</script>

<template>
  <ElDialog v-model="dict.form.on" :title @close="onResetForm">
    <ElForm label-width="auto" ref="formRef" :model="dict.form.items" :rules>
      <ElFormItem label="字典类型" required prop="dictType">
        <ElInput v-model="dict.form.items.dictType" />
      </ElFormItem>
      <ElFormItem label="字典名称" required prop="dictName">
        <ElInput v-model="dict.form.items.dictName" />
      </ElFormItem>
      <ElFormItem label="字典描述" prop="description">
        <ElInput v-model="dict.form.items.description" type="textarea" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="onResetForm">取消</ElButton>
      <ElButton type="primary" @click="onClickSubmitForm">确定</ElButton>
    </template>
  </ElDialog>
</template>
